<template>
    <div class="login-box">
        <div v-if="welcome" class="welcome">
            <van-circle v-model="currentTime"
                style="position: absolute; top: 10px; right: 10px;"
                size="56px"
                :rate="currentTime"
                v-on:click.native="closeWelcome"
                :text="`${time}s`"/>
            <i class="icon"></i>
            <span>{{welText}}</span>
        </div>
        <div v-else class="login">
            <div class="brand">
                <div class="brand-box">
                    <img src="../../images/wel-icon.png" alt="">
                    <span>让每个人都能享受科技的乐趣</span>
                </div>
            </div>

            <div class="ipt-box">
                <input v-model="loginObj.phone" type="text" placeholder="输入注册手机号">
            </div>
            <div class="ipt-box">
                <input v-model="loginObj.code" type="text" placeholder="输入验证码">
                <span @click="getVdtCode" class="btn">{{vdtText}}</span>
            </div>

            <van-checkbox v-model="remember" checked-color="#0B84FF">记住手机号？</van-checkbox>

            <van-checkbox v-model="auto" checked-color="#0B84FF">7天免登录？</van-checkbox>

            <van-button @click="loginEvt" 
            color="linear-gradient(to right, #ff6034, #0B84FF)"
            :loading="loading"
            loading-text="登录中..."
            :disabled="!/^1[3-9]{1}[0-9]{9}$/.test(loginObj.phone) || loginObj.code.length !== 4"
            block>登录</van-button>
            <span class="link" @click="$router.push('/register')">注册新用户？</span>
        </div>

        <div class="right">powered by qianqian tec &copy; 2022-3-10</div>
    </div>
</template>

<script>
    import { autoLoginApi, getUserInfoApi, getVdtCodeApi, loginApi } from '../../apis/loginApi'

    export default {

        data() {
            return {
                welcome: true,
                welText: [
                    '我听到了爆竹的声声催促 -- 正月',
                    '我闻到了腊梅的缕缕幽香 -- 如月',
                    '我看到了桃花绚烂如云霞 -- 蚕月',
                    '我躺在了柳阴中酣然入梦 -- 乏月',
                    '我品尝着晶莹剔透的樱桃 -- 蒲月',
                    '我观赏水莲花的绰约芳姿 -- 且月',
                    '我跃入那清波荡漾的碧水 -- 巧月',
                    '置身于桂花雨中翩然起舞 -- 壮月',
                    '我漫步在飘满落叶的小径 -- 玄月',
                    '我欣然采摘那累累的硕果 -- 良月',
                    '我聆听冬天走来的步履 -- 辜月',
                    '我掬起一捧洁白的雪花 -- 腊月'
                ][new Date().getMonth()],
                remember: false,
                auto: false,
                loginObj: {
                    phone: '',
                    code: ''
                },
                // 欢迎页面定时器
                timer: null,
                time: 5,
                currentTime: 100,
                // 免登录标识
                autoFlag: 'login',
                vdtText: '获取验证码',
                loading: false
            }
        },

        async created(){
            // 欢迎页面需要一个倒计时
            this.timer = setInterval(() => {
                if (this.currentTime > 0) {
                    this.currentTime -= 1
                    this.time = Math.ceil(this.currentTime / 20)
                    // console.log('------------', this.currentTime)
                } else {
                    // 倒计时到了，就需要把欢迎页面关闭
                    clearInterval(this.timer)
                    this.timer = null

                    if(this.autoFlag === 'success'){
                        this.$router.push('/home')
                    } else {
                        this.welcome = false
                    }
                }
            }, 50)

            // 读取免登录缓存 -- auto-text
            let autoText = localStorage.getItem('auto-text')

            // 如果有缓存则发送自动登录接口
            if (!!autoText) {
                // 自动登录业务
                // setTimeout(() => {
                //     this.autoFlag = 'success'
                // }, 2000)
                this.$store.commit('common/setToken', autoText)

                let result = await autoLoginApi()

                if(result.code === 200){
                    this.autoFlag = 'success'
                    this.$store.commit('common/setUserInfo', result.data)
                } else {
                    this.autoFlag = 'error'
                }
            } else {
                // 读取手机号缓存
                let userPhone = localStorage.getItem('user-phone')

                // 如果手机号存在 -- 给登录数据的phone赋值并且要把记住手机号的标识置为真
                if (!!userPhone) {
                    this.loginObj.phone = userPhone
                    this.remember = true
                }

                // 设置免登录失败
                this.autoFlag = 'error'
            }
        },
        methods:{
            closeWelcome() {
                console.log('-------------------------------')
                // 免登录进行中 -- 不执行任何业务
                if (this.autoFlag === 'login') return

                // 只要免登录完成以后都需要关闭定时器
                clearInterval(this.timer)

                // 登录成功
                if (this.autoFlag === 'success') {
                    this.$router.push('/home')
                } else {
                    this.welcome = false
                }
            },

            async loginEvt() {

                this.loading = true

                let result = await loginApi(this.loginObj)

                if(result.code !== 200){
                    this.$toast.fail('登录失败，请重试')
                    this.loading = false
                    return
                }

                this.$store.commit('common/setToken', result.data.token)

                let user = await getUserInfoApi(result.data.id)

                this.$store.commit('common/setUserInfo', result.data)

                // 判断用户是否同意免登录
                if (this.auto) {
                    localStorage.setItem('auto-text', result.data.token)
                } else {
                    localStorage.removeItem('auto-text')
                }

                // 用户同意记住手机号
                if (this.remember) {
                    localStorage.setItem('user-phone', this.loginObj.phone)
                } else {
                    localStorage.removeItem('user-phone')
                }
                
                this.$router.push('/home')
                
                // this.$router.push('/home')
            },

            async getVdtCode() {
                if(this.vdtText !== '获取验证码') return

                if(!/^1[3-9]{1}[0-9]{9}$/.test(this.loginObj.phone)){
                    this.$toast({
                        message: '请输入正确的手机号',
                        position: 'bottom'
                    })
                    return
                }

                this.vdtText = '正在获取...'

                let result = await getVdtCodeApi(this.loginObj.phone)
                if (result.code !== 200) {
                    this.$toast.fail('获取验证码失败，请重试')

                    // 需要重置节流标识
                    this.vdtText = '获取验证码'
                    return
                }

                this.$toast.success(`获取验证码成功，验证码：${result.data.code}`)

                this.loopTimer(Date.now())
            },

            // 递归实现倒计时
            loopTimer(_st) {
                let _pt = Math.ceil((Date.now() - _st) / 1000)
                this.vdtText = `重新获取(${5 - _pt}s)`
                setTimeout(() => { 
                    // 判断已经过去的时间要小于等待时间
                    if (_pt < 5) {
                        this.loopTimer(_st)
                    } else {
                        this.vdtText = '获取验证码'
                    }
                }, 100)
            }
        }
    }
</script>

<style lang="less" scoped>
    @import "../../style/common.less";

    .login-box {
        display: block;
        position: relative;
        height: 100%;
        padding: 4vh 20px 0;
        background-color: #fff;

        .welcome {
            .icon {
                display: block;
                margin: 16vh auto 0;
                width: 180px;
                height: 80px;
                background: url(../../images/wel-icon.png) center center / 100% 100% no-repeat;
            }
            > span {
                display: block;
                padding: 30px 0;
                font-size: .8rem;
                color: blank;
                text-align: center;
            }
        }

        .login {

            > .brand {
                display: block;
                margin: auto;
                width: 300px;
                height: 180px;
                > .brand-box{
                    width: 300px;
                    height: 84px;
                    margin-top: 48px;
                    text-align: center;
                    > img{
                        height: 48px;
                        width: 48px;
                        display: block;
                        border-radius: 30%;
                        overflow: hidden;
                        margin-left: 126px;
                        margin-bottom: 20px;
                    }
                    > span{
                        color: rgba(0,0,0,0.6);
                        font-size: 15px;
                    }
                }
            }
            > .ipt-box {
                display: flex;
                padding: 10px 0;
                margin-bottom: 16px;
                border-bottom: solid 1px @cdd;
                input {
                    flex: 1;
                    height: 32px;
                    background: transparent;
                    border: none;
                    outline: none;
                    text-indent: 12px;
                    font-size: .8rem;
                    // & 与input是同级样式
                    &::-webkit-input-placeholder {
                        font-size: .75rem;
                        color: @cdd;
                    }
                }

                .btn {
                    flex: 0 0 126px;
                    // flex设置以后，width是不生效的
                    // width: 150px;
                    border-left: solid 1px @cdd;
                    font-size: .7rem;
                    line-height: 32px;
                    text-align: center;
                }
            }

            .van-checkbox {
                margin-bottom: 16px;
                font-size: .75rem;
            }

            .link {
                display: block;
                margin: 16px 0;
                line-height: 32px;
                font-size: .75rem;
                color: #0B84FF;
            }
        }

        .right {
            position: absolute;
            left: 0;
            bottom: 16px;
            width: 100%;
            font-size: .65rem;
            color: @cdd;
            text-align: center;
        }
    }
</style>